package com.neu.wms.security;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.neu.wms.entity.SysUser;
import com.neu.wms.util.JwtUtils;
import com.neu.wms.util.RedisCache;
import com.neu.wms.util.ResultVo;
import com.neu.wms.vo.MenuVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.SimpleUrlAuthenticationSuccessHandler;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * @author DAIJUNQIANG
 * @version 1.0
 * @description 登录成功后，返回用户信息
 * @date 2023/7/3 15:58
 */
@Slf4j
public class LoginAuthenticationSuccessHandler extends SimpleUrlAuthenticationSuccessHandler {


	@Autowired
	private RedisCache redisCache;
	@Autowired
	private JwtUtils jwtUtils;

	@Override
	public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException {

		//通过SecurityContextHolder获取用户信息，底层是通过ThreadLocal获取
		SecurityContextHolder.getContext().setAuthentication(authentication);
		//根据用户名生成token 带给前端
		String token = jwtUtils.generateToken(authentication.getName());


		LoginUser loginUser = (LoginUser) authentication.getPrincipal();
		//把loginUser保存到redis中，七天后过期，减少每次请求对mysql的读操作
		redisCache.setCacheObject("neu:"+loginUser.getUsername(),loginUser,604800, TimeUnit.SECONDS);


		List<MenuVo> menuList = loginUser.getMenuVoList();

		SysUser user = loginUser.getUser();

		response.setContentType("application/json;charset=utf-8");
		String s = new ObjectMapper().writeValueAsString(ResultVo.ok("登录成功").data("menuList", menuList).data("token",token).data("user",user));
		log.info("token:{}",token);
		response.getWriter().println(s);
	}
}
